package com.joysuch.wwyt.api.sync.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.joysuch.wwyt.api.sync.SyncConstants;
import com.joysuch.wwyt.api.sync.SyncResponse;
import com.joysuch.wwyt.api.sync.bean.HiddenDangerAddBean;
import com.joysuch.wwyt.api.sync.bean.HiddenDangerEhsCheckBean;
import com.joysuch.wwyt.api.sync.service.HiddenDangerSender;
import com.joysuch.wwyt.core.entity.BaseConfig;
import com.joysuch.wwyt.core.service.BaseConfigService;
import com.joysuch.wwyt.core.support.Context;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import javax.servlet.http.HttpServletRequest;


@Slf4j
@Service
public class HiddenDangerSenderImpl implements HiddenDangerSender {

    @Autowired
    private BaseConfigService baseConfigService;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 隐患登记： 同步隐患登记记录
     * @return 同步接口返回信息
     */
    @Override
    public void addHiddenDanger(String formData, String taskName, String formKeyLabelJson, HttpServletRequest request) {

        if(!"隐患提交".equals(taskName)){
          return ;
        }
        log.info("... 隐患管理：新增登记开始 ... ");
        Long tenentId = Context.getCurrentTenantId();
        String companyCode = Context.getCompanyCode();
        BaseConfig urlConfig = baseConfigService.findConfig(tenentId,companyCode, SyncConstants.BASE_CONFIG_HIDDENDANGER_ADD_URL);
        BaseConfig serverUrlConfig = baseConfigService.findConfig(tenentId,companyCode, SyncConstants.BASE_CONFIG_SERVER_CONTEXT_URL);
        if(urlConfig != null && StringUtils.isNotEmpty(urlConfig.getValue())){
            try {
                String hiddenDangerJson = convertHiddenDanger(formData, formKeyLabelJson, serverUrlConfig);

                // 需求需要传参为json格式
                HttpHeaders header = new HttpHeaders();
                header.setContentType(MediaType.APPLICATION_JSON);
                //set body
                HttpEntity<String> requestBody = new HttpEntity<String>(hiddenDangerJson, header);
                log.info("... 隐患管理:新增登记发送url= {}, data={}" , urlConfig.getValue(), hiddenDangerJson);
                //post data
                ResponseEntity<SyncResponse> response = restTemplate.postForEntity(urlConfig.getValue(), requestBody, SyncResponse.class);
                log.info("... 隐患管理:新增登记发送成功: post response: " + response.getBody());
            }catch (Exception e){
                log.error("隐患管理:新增登记同步失败： url="+ urlConfig.getValue(),e);
            }
        }
    }

    private String convertHiddenDanger(String formData, String formKeyLabelJson, BaseConfig serverUrlConfig) {
        JSONObject formDataObj = JSON.parseObject(formData);
        JSONObject formLabelObj = JSON.parseObject(formKeyLabelJson);

        String id = formDataObj.getString("编号");
        String check_PERSONS = formDataObj.getString(formLabelObj.getString("上报人员"));
        //隐患名称
        String inv_NAME= formDataObj.getString(formLabelObj.getString("隐患名称"));
        //隐患描述
      //  String inv_RESULT= formDataObj.getString(formLabelObj.getString("隐患描述"));
        //上报时间（发现时间）
        String inv_TIME= formDataObj.getString(formLabelObj.getString("上报时间"));

        //严重程度
        String checkGrade= formDataObj.getString(formLabelObj.getString("隐患级别"));
        //隐患位置
        String dangerLocation= formDataObj.getString(formLabelObj.getString("隐患位置"));
        //责任单位
        String dutyDeptNo= formDataObj.getString(formLabelObj.getString("责任单位"));
        //部门负责人
        String deptDutyUser= formDataObj.getString(formLabelObj.getString("部门负责人"));
        //上传图片
       JSONArray files = formDataObj.getJSONArray(formLabelObj.getString("照片"));


        //录入人工号
        String oprid= Context.getCurrentCode();

        HiddenDangerEhsCheckBean ehsCheckBean = new HiddenDangerEhsCheckBean();
        ehsCheckBean.setId(id);
        ehsCheckBean.setCheck_PERSONS(check_PERSONS);
        ehsCheckBean.setInv_NAME(inv_NAME);
       // ehsCheckBean.setInv_RESULT(inv_RESULT);
        ehsCheckBean.setInv_TIME(inv_TIME);
        ehsCheckBean.setCheckGrade(checkGrade);
        ehsCheckBean.setDangerLocation(dangerLocation);
        ehsCheckBean.setDutyDeptNo(dutyDeptNo);
        ehsCheckBean.setDeptDutyUser(deptDutyUser);

        ehsCheckBean.setOprid(oprid);
        ehsCheckBean.setOrgCode(Context.getCompanyCode());

        HiddenDangerAddBean addBean = new HiddenDangerAddBean();
        addBean.setEhsCheck(ehsCheckBean);


        //上传图片列表
       JSONArray fileList = new JSONArray();
        if(files != null && !files.isEmpty()){
            String serverUrl = formatServerUrl(serverUrlConfig);
            for(int i=0;i<files.size();i++){
                JSONObject fileObj = new JSONObject();
                fileObj.put("filePath", serverUrl+files.get(i));
                fileList.add(fileObj);
            }
        }
        addBean.setFileList(fileList);
        return JSONObject.toJSONString(addBean);
    }


    private String formatServerUrl(BaseConfig baseConfig){
        String url = "http://192.168.10.51:8888";
        if(baseConfig != null && StringUtils.isNotEmpty(baseConfig.getValue())){
            url = baseConfig.getValue();
        }
        return url;
    }
}
